package com.huluobo.day11_im.chat.view;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.huluobo.day11_im.IMApp;
import com.huluobo.day11_im.R;
import com.huluobo.day11_im.adapter.MessageListAdapter;
import com.huluobo.day11_im.chat.presenter.ChatContract;
import com.huluobo.day11_im.chat.presenter.ChatPresenter;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;

import java.util.List;

public class MyChatActivity extends AppCompatActivity implements ChatContract.View {
    private ChatPresenter presenter;
    private ImageView back;
    private TextView title;
    private String username;

    private EditText chatEdit;

    private Button chatSend;

    private RecyclerView chatRecyclerView;
    private MessageListAdapter adapter;

    //接收消息的监听器
    private EMMessageListener messageListener = new EMMessageListener() {
        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            presenter.addMessage(username, messages);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    chatRecyclerView.getAdapter().notifyDataSetChanged();
                    scrollToBottom();
                }
            });
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_chat);
        presenter = new ChatPresenter(this);

        back = findViewById(R.id.header_back);
        title = findViewById(R.id.main_title);

        back.setVisibility(View.VISIBLE);

        EMClient.getInstance().chatManager().addMessageListener(messageListener);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        username = getIntent().getStringExtra(IMApp.CHAT_CONVERSATION_ID);
        title.setText(username);

        chatEdit = findViewById(R.id.chat_edit);
        chatSend = findViewById(R.id.chat_send);

        chatEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0) {
                    chatSend.setEnabled(true);
                } else {
                    chatSend.setEnabled(false);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        chatSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                presenter.sendMessage(chatEdit.getText().toString(), username);
            }
        });

        chatRecyclerView = findViewById(R.id.chat_recyclerView);
        chatRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new MessageListAdapter(presenter.messages);
        chatRecyclerView.setAdapter(adapter);
        presenter.loadMessage(username);

        chatRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                //当RecyclerView是一个空闲状态的时候,检查第一个item是否可见,代表是否滚动到顶部
                //SCROLL_STATE_IDLE 当前Recyclerview处于空闲状态
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    //检查第一个条目是否index是0
                    LinearLayoutManager linearLayoutManager =
                            (LinearLayoutManager) recyclerView.getLayoutManager();
                    if (linearLayoutManager != null) {
                        if (linearLayoutManager.findFirstVisibleItemPosition() == 0) {
                            presenter.loadMoreMessage(username);
                        }
                    }
                }
            }
        });
    }

    @Override
    public void onStartSendMessage() {

    }

    @Override
    public void onSendMessageSuccess() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                adapter.notifyDataSetChanged();
                chatEdit.setText("");
                scrollToBottom();
            }
        });

    }

    private void scrollToBottom() {
        chatRecyclerView.smoothScrollToPosition(presenter.messages.size() - 1);
    }

    @Override
    public void onSendMessageFailed(String error) {
        Log.i("TagA", "error:" + error);
    }

    @Override
    public void onMessageLoaded() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                chatRecyclerView.getAdapter().notifyDataSetChanged();
                scrollToBottom();
            }
        });
    }

    @Override
    public void onMoreMessageLoaded(int size) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                chatRecyclerView.getAdapter().notifyDataSetChanged();
                chatRecyclerView.smoothScrollToPosition(size);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EMClient.getInstance().chatManager().removeMessageListener(messageListener);
    }
}
